import ScrollBarLayout from '@/components/ScrollBarLayout';
import { Drawer, Empty, Menu, message, Spin } from 'antd';
import { useContext, useMemo, useState } from 'react';
import { IShortcutActionEnum } from '../common';
import { GlobalShortcutContext } from '../mconfig';
import { MinusOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { getPosIDs, getTenantID } from '@/utils';
import { ItemType } from 'antd/lib/menu/hooks/useItems';
import MyIcon from '@/components/MyIcon';
import { history } from 'umi';
import { ShortcutUpdateModal } from './ShortcutUpdateModal';
import { GlobalShortcutKeyAPI } from '../common/type';
import { editShortcutService } from '../services';
import _ from 'lodash';

export const ShortcutUpdateDrawer: React.FC<
  GlobalShortcutKeyAPI.IShortcutUpdateDrawer
> = () => {
  /**
   * 获取上下文共享数据
   */
  const {
    shortcutDispatch,
    shortcutCheckKey,
    prefixCls,
    userInfoObj,
    reloadUserInfoRun,
    curRes,
  } = useContext(GlobalShortcutContext);

  /**
   * 是否打开 新增快捷方式弹窗
   */
  const [showUpdateShortcut, setShowUpdateShortcut] = useState<any>({
    showOpen: false,
    shortcutType: '',
    shortcutItemObj: '',
  });

  /**
   * 鼠标移入, 显示按钮
   * @param id
   * @param flag
   * @returns
   */
  const onTreeNodeMouseEnter = (id: string, flag: boolean) => {
    const ele = document.getElementById(id);
    if (flag) {
      return;
    } else if (ele) {
      ele.style.display = 'block';
    }
  };

  /**
   * 鼠标移出清除按钮
   * @param id
   * @param flag
   * @returns
   */
  const onTreeNodeMouseLeave = (id: string, flag: boolean) => {
    const ele = document.getElementById(id);
    if (flag) {
      return;
    } else if (ele) {
      ele.style.display = 'none';
    }
  };

  /**
   * 是否拥有布局
   */
  const targetLayout = useMemo(() => {
    return userInfoObj?.muserLayoutList?.find((i: any) => {
      return (
        i?.layoutType === `${getTenantID()}10011000` &&
        i?.userPositionID == getPosIDs()
      );
    });
  }, [userInfoObj]);

  /**
   * 新增编辑后的回调
   */
  const updateShortcutCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadUserInfoRun();
    } else {
      message.error(res?.msg);
    }
  };

  /**
   * 编辑快捷方式
   */
  const { editShortcutLoading, editShortcutRun } = editShortcutService(
    updateShortcutCallback,
  );

  /**
   * 删除快捷方式
   */
  const deleteShortcut = (shortObj: any) => {
    let layoutInfo = targetLayout?.layoutInfo?.filter((item: any) => {
      return shortObj?.url != item?.url;
    });
    let editPayload: Record<string, any> = {
      layoutInfo: layoutInfo,
      id: targetLayout?.id,
      versionNum: targetLayout?.versionNum,
    };
    editShortcutRun(editPayload);
  };

  /**
   * 返回菜单快捷键
   */
  const shortcutBtnMemo = useMemo(() => {
    let newShorcutMenuItem: ItemType[] = [];

    targetLayout?.layoutInfo?.forEach((itemMenu: any) => {
      const idName = itemMenu?.url;
      let flag = false;
      let menuItemObj: any = {
        label: (
          <div
            className={prefixCls + 'shortcutDrawer-menuItemStyle-labelDivBox'}
            onClick={(e) => {
              e?.stopPropagation();
              history.push({
                pathname: itemMenu?.url,
              });
              shortcutDispatch({
                type: IShortcutActionEnum.CLEAR_RECEIVE,
              });
            }}
            onMouseEnter={() => {
              onTreeNodeMouseEnter(idName, flag);
            }}
            onMouseLeave={() => {
              onTreeNodeMouseLeave(idName, flag);
            }}
          >
            {itemMenu?.shortcutName}
            {curRes?.['/commonController/editLayout'] && (
              <div
                id={idName}
                style={{
                  display: flag ? 'block' : 'none',
                }}
              >
                <span
                  style={{ marginRight: 5 }}
                  onClick={(e) => {
                    e.stopPropagation();
                    setShowUpdateShortcut({
                      showOpen: true,
                      shortcutType: 'edit',
                      shortcutItemObj: itemMenu,
                    });
                  }}
                >
                  <MyIcon type="icon-edit1" />
                </span>
                <span
                  onClick={(e) => {
                    e.stopPropagation();
                    deleteShortcut(itemMenu);
                  }}
                >
                  <MyIcon type="icon-delete1" />
                </span>
              </div>
            )}
          </div>
        ),
        key: itemMenu?.url,
        icon: <MyIcon type={itemMenu?.iconType} />,
      };
      newShorcutMenuItem?.push(menuItemObj);
    });

    return newShorcutMenuItem;
  }, [userInfoObj, curRes]);

  return (
    <Drawer
      open={shortcutCheckKey == 'AddShortcut' ? true : false}
      title={
        <div className={prefixCls + 'shortcutDrawer-extraBtn'}>
          快速新建 &nbsp;
          <a
            onClick={() => {
              setShowUpdateShortcut({
                showOpen: true,
                shortcutType: 'add',
                shortcutItemObj: '',
              });
            }}
          >
            <PlusCircleOutlined />
          </a>
        </div>
      }
      placement="bottom"
      closable={false}
      getContainer={document.getElementById('root') as any}
      style={{
        position: 'absolute',
        width: '180px',
      }}
      height={280}
      headerStyle={{
        padding: '.5rem',
      }}
      mask={false}
      className={prefixCls + 'shortcutDrawer'}
      bodyStyle={{
        padding: 0,
      }}
      extra={
        <>
          <a
            onClick={() => {
              shortcutDispatch({
                type: IShortcutActionEnum.CLEAR_RECEIVE,
              });
            }}
          >
            <MinusOutlined />
          </a>
        </>
      }
    >
      <Spin spinning={editShortcutLoading}>
        <ScrollBarLayout>
          {shortcutBtnMemo && shortcutBtnMemo?.length > 0 ? (
            <>
              <Menu
                items={shortcutBtnMemo}
                className={prefixCls + 'shortcutDrawer-menuItemStyle'}
              />
            </>
          ) : (
            <>
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description={'暂无快捷方式'}
              />
            </>
          )}
        </ScrollBarLayout>
      </Spin>

      {/* 新增编辑快捷方式 */}
      {showUpdateShortcut?.showOpen && (
        <ShortcutUpdateModal
          open={showUpdateShortcut?.showOpen}
          onClose={() => {
            setShowUpdateShortcut({
              showOpen: false,
              shortcutType: '',
              shortcutItemObj: '',
            });
          }}
          shortcutType={showUpdateShortcut?.shortcutType}
          shortcutItemObj={showUpdateShortcut?.shortcutItemObj}
        />
      )}
    </Drawer>
  );
};
